package com.lanyun.aicorrectassistant.domain.userApiKey.impl;

import com.lanyun.aicorrectassistant.basic.bean.PageResult;
import com.lanyun.aicorrectassistant.basic.entity.AiModel;
import com.lanyun.aicorrectassistant.basic.entity.UserApiKey;
import com.lanyun.aicorrectassistant.basic.service.AiModelService;
import com.lanyun.aicorrectassistant.basic.service.UserApiKeyService;
import com.lanyun.aicorrectassistant.context.LoginContextHolder;
import com.lanyun.aicorrectassistant.controller.admin.userApiKey.vo.UserApiKeyRequestPageVO;
import com.lanyun.aicorrectassistant.controller.admin.userApiKey.vo.UserApiKeyRequestVO;
import com.lanyun.aicorrectassistant.controller.admin.userApiKey.vo.UserApiKeyResponseVO;
import com.lanyun.aicorrectassistant.convert.UserApiKeyConvert;
import com.lanyun.aicorrectassistant.domain.userApiKey.UserApiKeyDomainService;

import com.lanyun.aicorrectassistant.enums.IsDeletedFlagEnum;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户API密钥存储表领域服务实现
 *
 * @author Jqchan
 * @version 1.0
 * @date 2025-05-29 23:26:39
 */
@Service
public class UserApiKeyDomainServiceImpl implements UserApiKeyDomainService {

    @Resource
    private UserApiKeyService userApiKeyService;

    @Resource
    private AiModelService aiModelService;

    @Override
    public PageResult<UserApiKeyResponseVO> page(UserApiKeyRequestPageVO requestPageVO) {

        // 该用户是否已经插入大模型信息
        handlerIsAiModel();

        PageResult<UserApiKeyResponseVO> pageResult = new PageResult<>();
        UserApiKey queryEntity = UserApiKeyConvert.INSTANCE.convert(requestPageVO);
        queryEntity.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
        queryEntity.setUserId(LoginContextHolder.getLoginId());

        List<UserApiKey> entities = userApiKeyService.page(queryEntity,
                requestPageVO.getStart(), requestPageVO.getPageSize());

        if (entities.isEmpty()) {
            return pageResult;
        }

        Long count = userApiKeyService.count(queryEntity);
        List<UserApiKeyResponseVO> vos = UserApiKeyConvert.INSTANCE.convertEntityToRespList(entities);

        for (UserApiKeyResponseVO vo : vos) {
            Integer modelId = vo.getModelId();
            AiModel aiModel = aiModelService.queryById(modelId);
            vo.setModelName(aiModel.getModelName());
        }

        pageResult.setResult(vos);
        pageResult.setTotal(count.intValue());
        return pageResult;
    }

    private void handlerIsAiModel() {
        String userId = LoginContextHolder.getLoginId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        AiModel aiModel = new AiModel();
        aiModel.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
        aiModel.setIsEnabled(1);
        List<AiModel> aiModels = aiModelService.queryAllByCondition(aiModel);
        List<Integer> aiModelIds = aiModels.stream().map(AiModel::getId).toList();
        aiModelIds.forEach(aiModelId -> {
            UserApiKey queryEntity = new UserApiKey();
            queryEntity.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
            queryEntity.setModelId(aiModelId);
            queryEntity.setUserId(userId);
            if (userApiKeyService.queryByCondition(queryEntity) == null) {
                UserApiKey userApiKey = new UserApiKey();
                userApiKey.setModelId(aiModelId);
                userApiKey.setIsActive(0);
                userApiKey.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
                userApiKey.setUserId(userId);
                userApiKeyService.insert(userApiKey);
            }
        });
    }

    @Override
    public Boolean update(UserApiKeyRequestVO requestVO) {
        UserApiKey entity = UserApiKeyConvert.INSTANCE.convert(requestVO);
        return userApiKeyService.update(entity) != 0;
    }

    @Override
    public Boolean delete(Integer id) {
        UserApiKey entity = new UserApiKey();
        entity.setId(id);
        entity.setIsDeleted(IsDeletedFlagEnum.DELETED.getVal());
        return userApiKeyService.update(entity) != 0;
    }

    @Override
    public Boolean insert(UserApiKeyRequestVO requestVO) {
        UserApiKey entity = UserApiKeyConvert.INSTANCE.convert(requestVO);
        return userApiKeyService.insert(entity) != 0;
    }

    @Override
    public UserApiKeyResponseVO get(Integer id) {
        UserApiKey entity = userApiKeyService.queryById(id);
        UserApiKeyResponseVO userApiKeyResponseVO = UserApiKeyConvert.INSTANCE.convert(entity);
        if (userApiKeyResponseVO != null) {
            Integer modelId = userApiKeyResponseVO.getModelId();
            AiModel aiModel = aiModelService.queryById(modelId);
            userApiKeyResponseVO.setModelName(aiModel.getModelName());
        }
        return userApiKeyResponseVO;
    }
}
